package com.zx.mes.redis.hyl.controller;

import com.alibaba.fastjson.JSON;
import com.zx.mes.hyl.common.log.annotation.AroundLog;
import com.zx.mes.hyl.common.msg.ObjectRestResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisHash;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.TimeToLive;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * redis 测试
 * @author hyl
 * @date 2018-5-14
 */
@RequestMapping("/redis")
@RestController
public class RedisController {

    private Logger logger = LoggerFactory.getLogger(RedisController.class);

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @AroundLog(type = RedisController.class)
    @GetMapping("/test")
    public void test(){
        /* 字符串操作 */
        stringRedisTemplate.opsForValue().set("test","test",5, TimeUnit.MINUTES);
        /* 字符串获取 */
        logger.info(stringRedisTemplate.opsForValue().get("test"));
        /* 删除指定键 */
        stringRedisTemplate.delete("test");

        /* set 操作 */
        stringRedisTemplate.opsForSet().add("testSet","1","2");
        /* 获取集合成员 */
        logger.info(JSON.toJSONString(stringRedisTemplate.opsForSet().members("testSet")));
        /* 移除指定键成指定的成员 */
        stringRedisTemplate.opsForSet().remove("testSet", "1", "2");
        /* 删除集合 */
        stringRedisTemplate.delete("testSet");

        /* 列表操作 */
        stringRedisTemplate.opsForList().leftPushAll("testList", "1", "2");
        /* 获取列表中所有元素 */
        logger.info(JSON.toJSONString(stringRedisTemplate.opsForList().range("testList",0,-1)));

//        stringRedisTemplate.opsForList().remove()
        stringRedisTemplate.delete("testList");

    }

    /**
     *  "GET" "selectOne::12345678"  格式
     * @param id 12345678
     * @return String
     */
    @Cacheable(value = "selectOne",key = "#id")
    @GetMapping("/test2")
    @AroundLog(type=RedisController.class)
    public String test2(String id){
        logger.info("id:"+id);
        return "test2";
    }

    @Cacheable(value = "test3",keyGenerator = "keyGenerator")
    @GetMapping("/test3")
    @AroundLog(type = RedisController.class)
    public ObjectRestResponse<String> test3(){
        return new ObjectRestResponse<>().rel(true).data("test3");
    }
}
